import { getToken, setToken } from '@/util/auth'
import { captchaLogin } from '@/api/login'

const user = {
  state: () => ({
    token: getToken(),
    userInfo: JSON.parse(localStorage.getItem('USER'))
  }),
  mutations: {
    SET_TOKEN (state, token) {
      state.token = token
    },
    SET_USER (state, userInfo) {
      state.userInfo = userInfo
    }
  },
  actions: {
    captchaLogin ({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        captchaLogin(userInfo).then(response => {
          const { data } = response
          commit('SET_TOKEN', data.token)
          commit('SET_USER', data.user)
          setToken(data.token)
          localStorage.setItem('USER', JSON.stringify(data.user))
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    }
  },
  getters: { }
}
export default user
